<?php
namespace Admin\Controller;
use Common\Model\StoreModel;
use Common\Model\MemberModel;
use Common\Controller\AdminbaseController;
class StoreController extends AdminbaseController {

    public function index(){
        $adminInfo = session('ADMIN_ID');
        //搜索条件
        $keyword = trim(I('keyword'));
        if($keyword){
            $condition['ecm_member.user_name|ecm_store.store_name'] = array("like","%$keyword%");
        }

        $condition['ecm_store.store_id'] = array('neq',2);
        $cond['condition'] = $condition;

        //如果不是平台用户  取推广人id
        if($adminInfo['user_id'] != 2){
            $condition['ecm_store.extension_id'] = $adminInfo['user_id'];
            $cond['condition'] = $condition;
        }
        $storeModel = new StoreModel();

        $con = array(
            'condition' => $condition ,
            'order' => 'add_time desc'
        );
        $count = count($storeModel->getStoreCount($con));
        $p = I('p') ? I('p') : '1';
        $pageSize = I('pageSize') ? I('pageSize') : 15;
        $condition['ecm_store.store_id'] = array('neq',2);
        $condition['ecm_store.state'] = array('neq',3);
        $cond['condition'] = $condition;
        $cond = array(
            'condition' => $condition ,
            'page' => $p.','.$pageSize,
            'order' => 'add_time desc'
        );
        $res = $storeModel->getStoreList($cond);
        $this->assign("formget",array_merge($_GET,$_POST));
        $this->assign('store',$res);
        $page = $this->page($count, $pageSize);
        $this->assign("page", $page->show('Admin'));
    	$this->display();
    }

    public function changeAccount(){
        $res = D('account')->editAccountInfo(array('account_id'=>$_POST['id']),array('recommend_state'=>$_POST['recommend_state']));
        if($res === false){
            $return_array = array(
                'code' => '10010',
                'msg' => '修改状态失败'
            );
            echo json_encode($return_array);
            exit;
        }else{
            $return_array = array(
                'code' => '10000',
                'msg' => '修改状态成功'
            );
            echo json_encode($return_array);
            exit;
        }
    }

    function abslength($s){
        $n = 0;
        preg_match_all("/./us",$s,$matchs);
        foreach($matchs[0] as $p){
            $n += preg_match('#^['.chr(0x1).'-'.chr(0xff).']$#',$p) ? 1 : 2;
        }
        return $n;
    }

    public function insert(){
        if(!$_POST){
            $res = M('region')->where(array('parent_id'=>0))->select();
            $storeList = M("store")->where(array('parent_id'=>0,'store_type'=>'shops'))->select();
            $this->assign('storeList',$storeList);
            $this->assign('region1',$res);
            $this->display();
        }else{
            try{
                $data = $_POST;
                /**参数验证*/
                if(!$data['login_name'])$this->error('请输入用户名');
                if(!$data['password'])$this->error('请输入密码');
                if(!$data['confirm_password'])$this->error('请输入确认密码');
                if($data['password'] != $data['confirm_password'])$this->error('两次密码不一致');
                if(!$data['phone_mob'] || !$this->check_mobile($data['phone_mob']))$this->error('手机号格式错误');
                if($data['email'] && !$this->check_email($data['email']))$this->error('邮箱格式错误');
                if(!$data['store_name'])$this->error('请输入店家名称');
//                if(!$data['address'])$this->error('请输入地址');

                if($_POST['is_main'] == 0){
                    if(!$data['parent_id'] || $data['parent_id'] == 0){
                        $this->error('请选择店铺');
                    }
                }

                $memberModel = D("member");
                $storeModel = new StoreModel();
                $memberModel->startTrans();

                $whereMember['phone_mob'] = $data['phone_mob'];

                $memberInfo = $memberModel->where($whereMember)->find();
                if(!empty($memberInfo)){
                    $this->error('用户已存在！');
                }
                $time = time();
                $data_member = array(
                    'user_name' => $_POST['phone_mob'],
                    'password' => md5($_POST['password']),
                    'phone_mob' => $_POST['phone_mob'],
                    'email' => $_POST['email'],
                    'reg_time' => $time,
                );
                $res_member = $memberModel->add($data_member);
//

                $couponSettingModel = M("coupon_setting");
                $memberCouponModel = M('member_coupon');
                $register_coupon =$couponSettingModel->where('setting_id = 4')->find();
                $arr_coupon = array(
                    'coupon_name' => $register_coupon['name'],
                    'remark' => $register_coupon['remark'],
                    'money' => $register_coupon['money'],
                    'min_money' => $register_coupon['min_money'],
                    'user_id' => $res_member,
                    'start_time' => $time,
                    'end_time' => $time+$register_coupon['expiry_time'],
                    'is_used' => 0,
                );
                $add_register_coupon = $memberCouponModel->add($arr_coupon);

                $token = session_id();
                //保存到app_token表
                M('AppToken')->add(array(
                    'user_id' => $res_member,
                    'token' => md5('user_'.$res_member.'_'.'_'.time())
                ));
                $resMemberInfo = $storeModel->field("max(serial_number) as serial_number")->find();


                if(!$res_member){
                    $memberModel->rollback();
                    $this->error('添加用户失败');
                }
                if($_POST['region1']){
                    $region = $_POST['region1'];
                    $region_name = trim($_POST['region_name']);
                    if($_POST['region2']){
                        $region = $_POST['region2'];
                        $region_name = trim($_POST['region_name']).trim(M('region')->where(array('region_id'=>$region))->getField('region_name'));

                    }
                }
                if($data['attribution_code']){
                    $attribution_codeInfo = $storeModel->where(array("attribution_code"=>$data['attribution_code']))->find();
                    if($attribution_codeInfo){
                        $memberModel->rollback();
                        $this->error('店铺归属码已存在！');
                    }
                }

                //当前登录人id
                $sessionInfo = session('ADMIN_ID');
                $data_store = array(
                    'store_id'           => $res_member,
                    'store_name'         => $_POST['store_name'],
                    'login_password'     => md5($_POST['password']),
                    'login_name'         => $_POST['login_name'],
                    'region_id'          => $region,
                    'address'            => $_POST['address'],
                    'region_name'        => $region_name,
                    'state'              => 1,
                    'add_time'           => time(),
                    'is_main'            => 0,
                    'parent_id'          => $data['parent_id'],
                    'is_region_choice'   => $data['is_region_choice']?$data['is_region_choice']:0,
                    'serial_number'      => $resMemberInfo['serial_number'] + 1,
                    'extension_id'       => $sessionInfo['user_id'],
                    'logo_name'          => $_POST['logo_name'],
                    'min_sub'            => $data['min_sub'],
                    'max_sub'            => $data['max_sub']?$data['max_sub']:0.00,
                    'sub_money'          => $data['sub_money']?$data['sub_money']:0.00,
                    'store_logo'         => $data['store_logo']?'/promotion/data/upload/'.$data['store_logo']:'',
                    'attribution_code'   => $data['attribution_code'],
                    'attribution_switch' => $data['attribution_switch'],
                );
                $res_store = $storeModel->insertStoreInfo($data_store);
                if(!$res_store){
                    $memberModel->rollback();
                    $this->error('添加用户失败');
                }

                //生成二维码
                $dataEncrypt = $this->set_encrypt($res_member);
                $url = C('SITE_URL').'/mobile/index.php?app=qrcode&act=download&invite_code=' . $dataEncrypt;
                $pash = './uploads/qrcode/' .$res_member . '.png';
                $path = $this->create_png($url, false, $pash, 'H',10,6,false,'');
                $pUrl = 'promotion/uploads/qrcode/' . $res_member . '.png';
                $res_oss = $this->_upload($pUrl);
                if(!$res_oss){
                    $memberModel->rollback();
                    $this->error('上传oss失败！');
                }
                $save = $storeModel->where(array('store_id'=>$res_member))->save(array('qr_code'=>$pUrl));

                if($_POST['is_main'] == 0){
                    $first_class = $data['parent_id'];
                    $second_class = $res_member;
                }else{
                    $first_class = $res_member;
                    $second_class = 0;
                }
                $saveData = array('first_class'=>$first_class,'second_class'=>$second_class);
                $saveMember = $memberModel->where(array("user_id"=>$res_member))->save($saveData);
                if($save == false){
                    $memberModel->rollback();
                    $this->error('信息传输错误');
                }
                $memberModel->commit();

                $this->success('添加成功',U('Store/index'));
            }catch(\Exception $e){
                $this->error('网络错误');
                $memberModel->rollback();
            }
        }
    }
    public function qrcode(){
        require_once '../promotion/ThinkPHP/Library/Vendor/phpqrcode/phpqrcode.php';
        $qrcode = new \QRcode();
        $data = $_GET["data"];
        $url = 'http://www.cloud-moda.com/mobile/index.php?app=qrcode&act=download&invite_code='.$data;
        $qrcode->png($url,false);
    }

    public function revise(){
        $storeModel = new StoreModel();
        if(!$_POST){

            if (!$_GET['store_id']){
                $this->error('网络传输错误！');
            }
            $res = $storeModel->getStoreInfo(array('ecm_store.store_id'=>$_GET['store_id']));

            // 为了防止浏览器对修改的图片进行缓存，所以加一个临时变量v进行降噪处理，Powered by liuzongyang 2019/10/11 10:35
//            $res['store_logo'] = $res['store_logo'].'?v='.time();

            $token = M('AppToken')->where(array('user_id' => $_GET['store_id']))->find();
            if(empty($token)){
                $token['token'] = md5('user_'.$_GET['store_id'].'_'.'_'.time());
                M('AppToken')->add(array(
                    'user_id' => $_GET['store_id'],
                    'token' => $token['token']
                ));
            }
            $storeList = $storeModel->where(array('parent_id'=>0))->select();
            $this->assign('storeList',$storeList);
            $dataEncrypt = $this->set_encrypt($_GET['store_id']);
            $this->assign('dataEncrypt',$dataEncrypt);
            $this->assign('store',$res);
            $resRegion = M('region')->where(array('parent_id'=>0))->select();
            $this->assign('region1',$resRegion);
            $this->display();
        }else{

            $data = $_POST;
            /**参数验证*/
            if(!$data['store_id'])$this->error('store_id参数错误');
            if(!$data['login_name'])$this->error('请输入用户名');
            if(!$data['phone_mob'] || !$this->check_mobile($data['phone_mob']))$this->error('手机号格式错误');
            if($data['email'] && !$this->check_email($data['email']))$this->error('邮箱格式错误');
            if(!$data['store_name'])$this->error('请输入店铺名称');
//            if(!$data['address'])$this->error('请输入地址');
            if($data['min_sub'] && (!is_numeric($data['min_sub']) || $data['min_sub'] > 1)){
                $this->error('请填写正确的最低分佣比例！');
            }
            if($data['max_sub'] && (!is_numeric($data['max_sub']) || $data['max_sub'] > 1)){
                $this->error('请填写正确的最高分佣比例！');
            }
            if($data['sub_money'] && (!is_numeric($data['sub_money']) || $data['sub_money'] < 0 )){
                $this->error('销售总金额比较值！');
            }
            if($_POST['is_main'] == 0){
                if(!$data['parent_id'] || $data['parent_id'] == 0){
                    $this->error('请选择店铺');
                }
            }


            $res = $storeModel->getStoreInfo(array('ecm_store.store_id'=>$_POST['store_id']));
            $logopath = C('SITE_URL') . '/' . $res['store_logo'];
            //生成二维码
            if(!$res['qr_code']){
                $dataEncrypt = $this->set_encrypt($data['store_id']);
                $url = C('SITE_URL').'/mobile/index.php?app=qrcode&act=download&invite_code=' . $dataEncrypt;
                $pash = './uploads/qrcode/' .$data['store_id'] . '.png';
                $path_up = $this->create_png($url, false, $pash, 'H',10,6,false,'');
                $path = 'promotion/uploads/qrcode/' . $data['store_id'] . '.png';
                $res_oss = $this->_upload($path);
                if(!$res_oss){
                    $this->error('上传oss失败！');
                }
            }else{
                $path = $res['qr_code'];
            }

            $memberModel = new MemberModel();
            try{
                $whereMember['phone_mob'] = $data['phone_mob'];
                $whereMember['user_id'] = array('neq',$_POST['store_id']);
                $memberInfo = $memberModel->where($whereMember)->find();
                if(!empty($memberInfo)){
                    $this->error('用户已存在！');
                }

                $data_member = array(
                    'user_name' => $_POST['phone_mob'],
                    'phone_mob' => $_POST['phone_mob'],
                    'email' => $_POST['email'],
                );
                $res_member = $memberModel->reviseSellerInfo(array('user_id'=>$_POST['store_id']),$data_member);
                if($res_member  === false){
                    $memberModel->rollback();
                    $this->error('修改失败：修改个人信息失败');
                }

                if($_POST['region1']){
                    $region = $_POST['region1'];
                    if($_POST['region2']){
                        $region = $_POST['region2'];
                    }
                }

                $img = '/promotion/data/upload/'.$data['store_logo'];
                if($res['store_logo'] == $data['store_logo']){
                    $img = $data['store_logo'];
                }

                if($data['attribution_code']){
                    $attribution_codeInfo = $storeModel->where(array("attribution_code"=>$data['attribution_code'],'store_id'=>array("neq",$data['store_id'])))->find();
                    if($attribution_codeInfo){
                        $memberModel->rollback();
                        $this->error('店铺归属码已存在！');
                    }
                }

                $data_store = array(
                    'store_id'               => $_POST['store_id'],
                    'store_name'             => $_POST['store_name'],
                    'login_name'             => $_POST['login_name'],
                    'login_password'         => $data['password']?md5($data['password']):$res['login_password'],
                    'region_id'              => $region,
                    'address'                => $_POST['address'],
                    'region_name'            => trim($_POST['region_name']),
                    'state'                  => $_POST['state'],
                    'is_main'                => 0,
                    'parent_id'              => $data['parent_id'],
                    'is_region_choice'       => $data['is_region_choice']?$data['is_region_choice']:0,
                    'qr_code'                => $path,
                    'logo_name'              => $_POST['logo_name'],
                    'min_sub'                => $data['min_sub'],
                    'max_sub'                => $data['max_sub']?$data['max_sub']:0.00,
                    'sub_money'              => $data['sub_money']?$data['sub_money']:0.00,
                    'settlement_method'      => $data['settlement_method'],
                    'store_logo'             => $img,
                    'attribution_code'   => $data['attribution_code'],
                    'attribution_switch' => $data['attribution_switch'],
                );
                $storeModel->where(array('store_id'=>$_POST['store_id']))->save($data_store);
                $memberModel->commit();
                $this->success('保存成功',U('Store/index'));
            }catch(\Exception $e){
                $this->error('网络错误');
                $memberModel->rollback();
            }
        }
    }


    //开启关闭
    public function check(){
        $storeModel = new StoreModel();
        if(isset($_POST['ids']) && $_GET["state"] == 1){
            $ids = I('post.ids/a');

            if ( $storeModel->where(array('store_id'=>array('in',$ids)))->save(array('state'=>1)) !== false ) {
                $this->success("开启成功！");
            } else {
                $this->error("开启失败！");
            }
        }
        if(isset($_POST['ids']) && $_GET["state"] == 2){
            $ids = I('post.ids/a');

            if ( $storeModel->where(array('store_id'=>array('in',$ids)))->save(array('state'=>2)) !== false) {
                $this->success("关闭成功！");
            } else {
                $this->error("关闭失败！");
            }
        }
    }

    // 删除
    public function delete(){
        $storeModel = new StoreModel();
        if(isset($_GET['id'])){
            $id = I("get.id",0,'intval');
            if ($storeModel->where(array('id'=>$id))->save(array('post_status'=>3)) !==false) {
                $this->success("删除成功！");
            } else {
                $this->error("删除失败！");
            }
        }

        if(isset($_POST['ids'])){
            $ids = I('post.ids/a');

            if ($storeModel->where(array('store_id'=>array('in',$ids)))->save(array('state'=>3))!==false) {
                $this->success("删除成功！");
            } else {
                $this->error("删除失败！");
            }
        }
    }

    public function getRegion(){
        if(!$_POST['parent_id']){
            $return_array = array(
                'code' => '10010',
                'msg' => '参数错误'
            );
            echo json_encode($return_array);
            exit;
        }
        $res = M('region')->where(array('parent_id'=>$_POST['parent_id']))->select();
        if(!$res){
            $return_array = array(
                'code' => '10020',
                'msg' => '获取城市列表失败'
            );
            echo json_encode($return_array);
            exit;
        }else{
            $return_array = array(
                'code' => '10000',
                'msg' => '获取城市列表成功',
                'data' => $res
            );
            echo json_encode($return_array);
            exit;
        }
    }


    //获取总店铺下属店铺
    public function get_son_storeList($store_id=null){
        return D("store")->where(array("parent_id"=>$store_id))->select();
    }


    //获取当前店铺的小程序码
    public function getAppletCode(){
        $store_id = I("post.store_id");
        $code = -1;
        $msg = '参数错误';
        if($store_id){
            $storeModel = D("store");
            $storeInfo = $storeModel->where(array('store_id'=>$store_id))->find();
            $msg = '店铺信息异常';
            if($storeInfo){
//                $msg = '请填写小程序抬头名称';
//                if($storeInfo['logo_name']){
                    $file_name = $store_id.rand(100,999).time().'.png';
                    $file = '../data/files/wx_applet_store/store_'.$store_id.'/'.$file_name;
                    $appid = C('WX_APPLET_APPID');
                    $secret = C('WX_APPLET_APPSECRET');

                    $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret;
                    // get请求获取access_token
                    $data = $this->getCurl($url);
                    $data = json_decode($data,true);
                    $msg = '获取微信access_token失败';
                    if($data['access_token']){
                        //获取二维码
                        //参数
                        $postdata['scene']='storeid='.$storeInfo['store_id'];
                        // 宽度
                        $postdata['width']=1280;
                        // 页面
                        $postdata['page']='pages/index/index';
                        // 线条颜色
                        $postdata['auto_color']=false;
                        //auto_color 为 false 时生效
                        $postdata['line_color']=array('r'=>'0','g'=>'0','b'=>'0');
                        // 是否有底色为true时是透明的
                        $postdata['is_hyaline']=false;
                        $post_data = json_encode($postdata);

                        // 获取二维码
                        $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=".$data['access_token'];
                        // post请求
                        $result = $this->postCurl($url,$post_data);

                        // 保存二维码
                        $path_log = '../data/files/wx_applet_store/store_'.$store_id.'/';
                        mkdirs_1($path_log, 0777, true);
                        file_put_contents($file,$result);
                        //上传到oss
                        $pash = 'data/files/wx_applet_store/store_'.$store_id.'/'.$file_name;
                        $oss = $this->_upload($pash);
                        $msg = '上传oss失败！';
                        if($oss){
                            $save = $storeModel->where(array("store_id"=>$store_id))->save(array('applet_code'=>$pash));
                            $msg = '添加失败';
                            if($save){
                                $code = 1;
                                $msg = '添加成功';
                            }
                        }
                    }
//                }
            }
        }
        echo json_encode(array("code"=>$code,"msg"=>$msg));
        exit();
    }

}
function mkdirs_1($path, $mode = 0777){
    if(is_dir($path)){
        return '无法创建,已经是目录了';
    }else{
        if(mkdir($path, $mode, true)) {
            return '创建成功';
        }else{
            return '创建失败';
        }
    }
}